package com.jj.interceptor;

import com.jj.annotatiion.Role;
import com.jj.entity.menu;
import com.jj.entity.userlogin;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.List;

public class RoleInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("进来了拦截器");
        if (!(handler instanceof HandlerMethod)){
            System.out.println("转换");
            return true;
        }
        Method method = ((HandlerMethod) handler).getMethod();
        Role role = method.getAnnotation(Role.class);
        if (role==null){
            return true;
        }
        //获取注解中的menucode
        String value = role.value();
        //获取当前用户的ID
        HttpSession session = request.getSession();
        userlogin user =(userlogin) session.getAttribute("user");
        //获取当前登录用户的权限
        List<menu> menus =(List<menu>) redisTemplate.opsForValue().get("se");
        for (menu menu : menus) {
            if (menu.getMenu_code().equals(value)) {
                return true;
            }
        }
        request.getRequestDispatcher("/u/t2").forward(request,response);
        return false;
    }
}
